﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.IO;
using System.Reflection;
using Office = Microsoft.Office.Core;
using VBIDE = Microsoft.Vbe.Interop;
using Excel = Microsoft.Office.Interop.Excel;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using Microsoft.Vbe.Interop;


namespace CreateMacro
{
    public partial class testMacro : Form
    {
        public testMacro(string path)
        {
            InitializeComponent();
            load(path);
        }
        [DllImport("user32.dll")]
        public static extern bool LockWindowUpdate(IntPtr hWndLock);
        private string[] lines;
        public Regex keyWords = new Regex("AddHandler|AndAlso|Byte|Catch|CDate|CInt|Const|CSng|CULng|Declare|DirectCast|Else|Enum|Exit|Friend|GetXMLNamespace|Handles|Imports (.NET Namespace and Type)|Integer|Let|Loop|MustInherit|Namespace|Not|Object|Option|Overloads|Partial|Public|REM|SByte|Shared|Step|Sub|To|TypeOf|ULong|While|WriteOnly|#ElseIf" +
         "#End|Xor|Widening|UShort|True|SyncLock|Stop|Short|Select|RemoveHandler|RaiseEvent|Private|Overridable|Optional|Of|Nothing|Narrowing|MustOverride|Me|Lib|Interface|Imports|If|Global|Function|False|Erase|ElseIf|Do|Default|CUShort|CStr|Continue|Class|CDec|CBool|ByVal|As|AddressOf" +
         "Alias|Boolean|Call|CByte|CDbl|CLng|CSByte|CType|Date|Delegate|Double|End|Error|Finally|Get|GoSub|If()|In|Is|Like|Mod|MyBase|New|NotInheritable|On|Or|Overrides|Property|ReadOnly|Resume|Set|Single|String|Then|Try|Wend|Using|With|#Const|#If" +
         "#Else|WithEvents|When|UInteger|TryCast|Throw|Structure|Static|Shadows|Return|ReDim|Protected|ParamArray|Operator|OrElse|NotOverridable|Next|MyClass|Module|Long|IsNot|Inherits|Implements|GoTo|GetType|ForEvent|EndIf|Each|Dim|Decimal|CUInt|CShort|CObj|Char|CChar|Case|ByRef|And|");
        private void hightlight()
        {
            try
            {
                LockWindowUpdate(richTextBox1.Handle);
                int selPos = richTextBox1.SelectionStart;
                foreach (Match keyWordMatch in keyWords.Matches(richTextBox1.Text))
                {
                    richTextBox1.Select(keyWordMatch.Index, keyWordMatch.Length);
                    richTextBox1.SelectionColor = Color.Blue;
                    richTextBox1.SelectionStart = selPos;
                    richTextBox1.SelectionColor = Color.Black;
                }
            }
            finally { LockWindowUpdate(IntPtr.Zero); }
        }
        private void load(string path)
        {
            if (path != "")
            {
                txtSource.Text = path;
                string core = "";
                if (File.Exists(path))
                {
                    lines = File.ReadAllLines(path);
                    foreach (var items in lines)
                    {
                        core += items.ToString() + "\r\n";
                    }
                    richTextBox1.Text = core;
                }
            }
        }
        private bool checkMacro()
        {
            Excel.Application oExcel;
            Excel.Workbook oBook;
            VBIDE.VBComponent oModule;
            String sCode;
            try
            {
                string filetest = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), @"test.xlsx");
                Object oMissing = System.Reflection.Missing.Value;
                oExcel = new Excel.Application();
                oBook = oExcel.Workbooks.Add(oMissing);
                bool IsPass = oBook.HasPassword;
                Object misValue = System.Reflection.Missing.Value;
                if (!IsPass)
                {
                    oExcel.DisplayAlerts = false;
                    oBook = oExcel.Workbooks.Open(filetest, false, true, Type.Missing, string.Empty, string.Empty, true, Type.Missing, Type.Missing, false, false, Type.Missing, false, true, Type.Missing);
                }
                else
                {
                    oBook = oExcel.Workbooks.Open(filetest, false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, false, false, Type.Missing, false, true, Type.Missing);
                }
                oModule = oBook.VBProject.VBComponents.Add(VBIDE.vbext_ComponentType.vbext_ct_StdModule);
                sCode = richTextBox1.Text;
                oModule.CodeModule.AddFromString(sCode);
                try
                {
                    //oBook.SaveAs(filepath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);

                    oBook.Application.Run(txtSub.Text, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
                       oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
                       oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
                       oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
                    //  oBook.EnvelopeVisible = false;
                    // oBook.RunAutoMacros(Excel.XlRunAutoMacro.xlAutoActivate);
                }
                catch
                {
                    return false;
                }
                finally
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oBook);
                    oExcel.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel);
                    GC.Collect();
                }

            }
            catch
            {
                return false;
            }

            return true;
        }
        private void Run_Click(object sender, EventArgs e)
        {
            if (richTextBox1.Text != "" && txtSub.Text != "")
            {
                if (checkMacro() == true)
                {
                    MessageBox.Show("ok");
                }
            }
            else
            {
                MessageBox.Show("Name sub và source không được trống");
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = "Text Files (.txt)|*.txt";
            openFileDialog1.Title = "Chọn File Macro";
            openFileDialog1.ShowDialog();
            var file = openFileDialog1.FileName;
            txtSource.Text = file;
            string core = "";
            if (File.Exists(file))
            {
                lines = File.ReadAllLines(file);
                foreach (var items in lines)
                {
                    core += items.ToString() + "\r\n";
                }
                richTextBox1.Text = core;
            }
            hightlight();
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            hightlight();
        }
    }
}
